/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.admin;

import entity.Company;
import entity.Department;
import entity.Division;
import entity.Message;
import entity.Users;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.CompanyFacade;
import session.DepartmentFacade;
import session.DivisionFacade;
import session.MessageFacade;
import session.UsersFacade;

/**
 *
 * @author owtee
 */
public class UserAdd extends HttpServlet {

    @EJB
    private DivisionFacade divisionFacade;
    @EJB
    private CompanyFacade companyFacade;
    @EJB
    private DepartmentFacade departmentFacade;
    @EJB
    private UsersFacade usersFacade;
    @EJB
    private MessageFacade messageFacade;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            try {
                String txtUserId = request.getParameter("txtUserId");
                String txtUserPwd = request.getParameter("txtUserPwd");
                String txtUserRePwd = request.getParameter("txtUserRePwd");
                String ddlCom = request.getParameter("ddlCom");
                String ddlDiv = request.getParameter("ddlDiv");
                String ddlDep = request.getParameter("ddlDep");
                String txtFirstName = request.getParameter("txtFirstName");
                String txtLastName = request.getParameter("txtLastName");
                String txtTelephone = request.getParameter("txtTelephone");
                boolean chkAdminFlag = (request.getParameter("chkAdminFlag") == null ? false : true);
                boolean chkMsgFlag = (request.getParameter("chkMsgFlag") == null ? false : true);

                // Validate data
                List<Message> mesLst = new ArrayList<Message>();

                if (txtUserId.equals("")) {
                    Message message = messageFacade.find("016");
                    mesLst.add(message);
                } else {
                    Users user = usersFacade.find(txtUserId);
                    if (user != null) {
                        Message message = messageFacade.find("021");
                        mesLst.add(message);
                    }
                }

                if (txtUserPwd.equals("")) {
                    Message message = messageFacade.find("017");
                    mesLst.add(message);
                }

                if (!txtUserPwd.equals(txtUserRePwd)) {
                    Message message = messageFacade.find("018");
                    mesLst.add(message);
                }

                if (ddlCom.equals("")) {
                    Message message = messageFacade.find("034");
                    mesLst.add(message);
                }

                if (ddlDiv.equals("")) {
                    Message message = messageFacade.find("035");
                    mesLst.add(message);
                }

                if (ddlDep.equals("")) {
                    Message message = messageFacade.find("005");
                    mesLst.add(message);
                }

                if (txtFirstName.equals("")) {
                    Message message = messageFacade.find("019");
                    mesLst.add(message);
                }

                if (txtLastName.equals("")) {
                    Message message = messageFacade.find("020");
                    mesLst.add(message);
                }

                if (txtTelephone.equals("")) {
                    Message message = messageFacade.find("010");
                    mesLst.add(message);
                }

                if (mesLst.size() > 0) {
                    List<Company> comLst = companyFacade.findByActiveFlag(true);

                    Users user = new Users();
                    user.setUserId(txtUserId);
                    user.setEmpFirstName(txtFirstName);
                    user.setEmpLastName(txtLastName);
                    user.setTelephone(txtTelephone);
                    user.setAdminFlag(chkAdminFlag);
                    user.setMsgFlag(chkMsgFlag);
                    if (!ddlCom.equals("")) {
                        Company com = companyFacade.find(Integer.parseInt(ddlCom));
                        user.setComId(com);

                        List<Division> diviLst = (List<Division>) com.getDivisionCollection();
                        request.setAttribute("diviLst", diviLst);
                        List<Department> depLst = (List<Department>) com.getDepartmentCollection();
                        request.setAttribute("depLst", depLst);

                        if (!ddlDiv.equals("")) {
                            user.setDivId(divisionFacade.find(Integer.parseInt(ddlDiv)));
                        }

                        if (!ddlDep.equals("")) {
                            user.setDepId(departmentFacade.find(Integer.parseInt(ddlDep)));
                        }
                    }

                    request.setAttribute("user", user);
                    request.setAttribute("comLst", comLst);
                    request.setAttribute("mesLst", mesLst);

                    RequestDispatcher rd = request.getRequestDispatcher("user_add.jsp");
                    rd.forward(request, response);

                    return;
                }
                // End Validate data

                // Get session
                HttpSession session = request.getSession();
                Users member = (Users) session.getAttribute("member");

                //Find menu role
                // Set default to normal
                String menuRole = "E";
                if (chkAdminFlag == true) {
                    // Set to admin
                    menuRole = "A";
                } else {
                    if (chkMsgFlag == true) {
                        // Set to messenger
                        menuRole = "M";
                    }
                }

                Users user = new Users();
                user.setUserId(txtUserId);
                user.setUserPwd(txtUserPwd);
                user.setComId(companyFacade.find(Integer.parseInt(ddlCom)));
                user.setDivId(divisionFacade.find(Integer.parseInt(ddlDiv)));
                user.setDepId(departmentFacade.find(Integer.parseInt(ddlDep)));
                user.setEmpFirstName(txtFirstName);
                user.setEmpLastName(txtLastName);
                user.setTelephone(txtTelephone);
                user.setAdminFlag(chkAdminFlag);
                user.setMsgFlag(chkMsgFlag);
                user.setMenuRole(menuRole);
                user.setActiveFlag(true);
                user.setCreateUser(member.getUserId());
                user.setCreateDate(new Date());
                user.setModifyUser(member.getUserId());
                user.setModifyDate(new Date());
                usersFacade.create(user);

                Message message = messageFacade.find("101");
                request.setAttribute("message", message);

            } catch (Exception ex) {
                // Found error
                Message message = messageFacade.find("002");
                String m = message.getMesDetail() + " : " + ex.getMessage();
                message.setMesDetail(m);
                request.setAttribute("message", message);
            }

            RequestDispatcher rd = request.getRequestDispatcher("UserGetAll");
            rd.forward(request, response);

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
